package com.logicwin.aibala.model.androidSWInfo;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.content.Intent;
import android.content.pm.*;
import android.net.Uri;
import android.util.Log;

import com.logicwin.aibala.action.LoadSearchAction;
import com.logicwin.aibala.com.AibalaException;
import com.logicwin.aibala.com.GlobalConfig;
import com.logicwin.aibala.system.sqlite.SQLiteService;

/**
 * Android软件信息服务类
 * 
 * @author GuoDing
 * @since 2011-05-27
 */
public final class AndroidSWInfoService {
	private AndroidSWInfoService() {
	}
	
	public static final String CLASS_ID_INDEX = "index";             //首页
	public static final String CLASS_ID_GAME = "games";            //炫动游戏
	public static final String CLASS_ID_ENTER = "entertainment";   //影音娱乐
	public static final String CLASS_ID_SNS = "sns";        //网络社交
	public static final String CLASS_ID_MEDIA = "media";            //生活媒体
	public static final String CLASS_ID_OFFICE = "office";         //商务办公
	public static final String CLASS_ID_SYS = "systool";          //系统工具
	
	public static final String SORT_ID_BEST = "best";               //最热
	public static final String SORT_ID_NEW = "new";               //最新
	public static final String SORT_ID_RANK = "rank";         //排行
	
	private static List<APKListItem> apkList = null;
	
	/**
	 * 本机安装软件信息
	 */
	private static Object apkInstallListLock = new Object();
	private static List<APKInstallInfo> apkInstallList = null;
	private static Context myCtx = null;
	
	private static Map<String,List<APKListItem>> apkListMap = new HashMap<String,List<APKListItem>>();
	
	
	/**
	 * 初始化服务
	 * @throws AibalaException
	 */
	public static void init(Context ctx) throws AibalaException {
		try {
			myCtx = ctx;
			updateAPKInstallInfo();
		} catch(Exception e) {
			Log.e("", "", e);
			throw new AibalaException(e);
		}
	}
	
	/**
	 * 关闭服务
	 */
	public static void destroy() {
		
	}
	
	/**
	 * 获取最热列表 
	 * @param classID: 炫动游戏，影音娱乐，网络社交，生活媒体，商务办公，系统工具
	 * @return
	 */
	
	public static List<APKListItem> getHotList(String classID) {
//		return getAndroidSWList(classID, SORT_ID_HOT,0);
		return null;
	}

	/**
	 * 获取列表页信息
	 * @param sortType: 最新，最热，排行
	 * @param classType: 首页，炫动游戏，影音娱乐，网络社交，生活媒体，商务办公，系统工具
	 * @return
	 */
	public static String[] getSearchList() {

		return LoadSearchAction.getSearchKeywords();
//		return SQLiteService.getAndroidSWList(sortType, classType);
	}
	
	public static List<APKListItem> getSearchResult(String keyword){
		return LoadSearchAction.getSearchList(keyword);
	}
	
	/**
	 * 获取列表页信息
	 * @param sortType: 最新，最热，排行
	 * @param classType: 首页，炫动游戏，影音娱乐，网络社交，生活媒体，商务办公，系统工具
	 * @return
	 */
	public static List<APKListItem> getAndroidSWList(String classType, String sortType, int page) {
//		return apkListMap.get(classType+"_"+sortType+"_"+page);
		
		List<APKListItem> list = apkListMap.get(classType+"_"+sortType+"_"+page);
		
		Log.i("AndroidSWInfoService","getAndroidSWList  key="+classType+"_"+sortType+"_"+page+"  list="+list);
		return list;
//		return SQLiteService.getAndroidSWList(sortType, classType);
	}
	
	/**
	 * 加载下一页信息
	 * @param sortType: 最新，最热，排行
	 * @param classType: 首页，炫动游戏，影音娱乐，网络社交，生活媒体，商务办公，系统工具
	 */
	public static void loadNextPage(List<APKListItem> currentList, String classType, String sortType) {
		List<APKListItem> apkList = apkListMap.get(classType+"_"+sortType+"_0");
		
		int count = apkList.size();
		
		for (int i=0;i<count;i++){
			currentList.add(apkList.get(i));
		}
	}
	
	public static void setAPKList(String classType, String sortType, int page, List<APKListItem> apkList){
		Log.i("AndroidSWInfoService","setAPKList  key="+classType+"_"+sortType+"_"+page+"  list="+apkList);
		apkListMap.put(classType+"_"+sortType+"_"+page, apkList);
	}
	
	/**
	 * 获取aibala软件在本机的安装状态
	 * 
	 * @param pkgName: 软件包名称
	 * @param versionCode: 版本号字符
	 * @return: APKInstallInfo.INSTALL_STAT_NO_INSTALL  没有安装
	 *          APKInstallInfo.INSTALL_STAT_HAS_INSTALL 已经安装，并且没有更新
	 *          APKInstallInfo.INSTALL_STAT_NEED_UPDATE 已经安装，并且有更新
	 */
	public static int getAPKInstallState(String pkgName, String versionCode) {
		int ret = APKInstallInfo.INSTALL_STAT_NO_INSTALL;
		
		synchronized(apkInstallListLock) {
			for(APKInstallInfo ai : apkInstallList) {
				if(0 == pkgName.compareTo(ai.getPackageName())) {
					if(0 == versionCode.compareTo(ai.getCurrVersion())) {
						ret = APKInstallInfo.INSTALL_STAT_HAS_INSTALL;
					}
					else {
						ret = APKInstallInfo.INSTALL_STAT_NEED_UPDATE;
					}
					break;
				}
			}
		}
		
		return ret;
	}
	
	public static List<APKInstallInfo> getAPKInstallList() {
		return apkInstallList;
	}
	
	/**
	 * 安装APK文件
	 * @param apkFileName：要安装的APK文件名称(下载下来后，都自动存放在系统默认的目录下)
	 * @throws AibalaException
	 */
	public static void installAPK(String apkFileName) {
		Uri filurl = Uri.fromFile(new File(GlobalConfig.getAPKDownloadDir() + "/" + apkFileName));
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setDataAndType(filurl, "application/vnd.android.package-archive");     
		myCtx.startActivity(intent);  
	}
	
	/**
	 * 删除已经安装的APK
	 * @param packageName：包名
	 */
	public static void uninstallAPK(String packageName) {
		Uri packageURI = Uri.parse("package: " + packageName);        
		Intent intent = new Intent(Intent.ACTION_DELETE, packageURI);    
		myCtx.startActivity(intent);  
	}
	
	/**
	 * 更新本机软件安装状态，调用情况：
	 * 1.初始化
	 * 2.安装，更新，卸载过了以后
	 * 
	 * @param ctx
	 */
	public static void updateAPKInstallInfo() {
		List<PackageInfo> apps = new ArrayList<PackageInfo>();  
		PackageManager pManager = myCtx.getPackageManager(); 
		List<PackageInfo> paklist = pManager.getInstalledPackages(0);
		for (int i = 0; i < paklist.size(); i++) {
			PackageInfo pak = (PackageInfo) paklist.get(i);
			// 判断是否为非系统预装的应用程序
			if ((pak.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) <= 0) {
				apps.add(pak);
			}
		}
		
		synchronized(apkInstallListLock) {
			apkInstallList.clear();
			for(PackageInfo pi : apps) {
				APKInstallInfo ai = new APKInstallInfo(pi);
				apkInstallList.add(ai);
			}
		}
	}
	
}













